import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Box, Typography, Menu, MenuItem, Button } from '@mui/material';
import { styled } from '@mui/material/styles';
import VisitorCounter from 'components/electrons/VisitorCounter';
import AdaptiveLayout from 'components/elements/AdaptiveLayout';
import {
  getMenuButtonStyles,
  getStyledMenuItemStyles,
  getMenuContainerStyles,
  getMenuSx,
  getAdaptiveLayoutProps,
  getVisitorCounterSx
} from './sxobjects';

// Styled components with darkMode support
const MenuButton = styled(Button)(({ darkmode }) => getMenuButtonStyles(darkmode === 'true'));

const StyledMenuItem = styled(MenuItem)(({ darkmode }) => getStyledMenuItemStyles(darkmode === 'true'));

const MenuContainer = styled(Box)(({ darkmode }) => getMenuContainerStyles(darkmode === 'true'));

const Footer = ({
  display = true,
  paddingY = 0,
  paddingX = 0,
  backgroundColor = 'transparent',
  innerBackgroundColor = 'transparent',
  color = 'primary.main',
  fontWeight = 400,
  darkMode = false
}) => {
  const navigate = useNavigate();
  const [anchorEls, setAnchorEls] = useState({});

  const navigatePage = (url) =>
    window.open(url, '_blank', 'noopener,noreferrer');

  const navigateOpen = (path) => {
    if (path?.startsWith('http')) {
      navigatePage(path);
    } else if (path) {
      navigate(path);
    }
  };

  const handleMenuClick = (event, menuId) => {
    setAnchorEls(prev => ({
      ...prev,
      [menuId]: event.currentTarget
    }));
  };

  const handleMenuClose = (menuId) => {
    setAnchorEls(prev => ({
      ...prev,
      [menuId]: null
    }));
  };

  const handleMenuItemClick = (path, menuId) => {
    navigateOpen(path);
    handleMenuClose(menuId);
  };

  const menuSections = [
    {
      id: 'public',
      title: 'Public',
      items: [
        { label: 'Home', path: '/' },
        { label: 'Home Page', path: '/home-page' },
        { label: 'Hello World', path: '/hello-world' }
      ]
    },
    {
      id: 'auth',
      title: 'Auth',
      items: [
        { label: 'Login', path: '/auth/login' },
        { label: 'Register', path: '/auth/register' },
        { label: 'Forgot Password', path: '/auth/forgot-password' },
        { label: 'Resend Activation', path: '/auth/resend-activation' },
        { label: 'Reset Password' },
        { label: 'Activate Account' }
      ]
    },
    {
      id: 'users',
      title: 'Users',
      items: [
        { label: 'All Users', path: '/users' },
        { label: 'Create User', path: '/create-user' },
        { label: 'Edit User', path: '/user/edit' },
        { label: 'Edit Account', path: '/account/edit' },
        { label: 'Edit User ID' },
        { label: 'User Detail' }
      ]
    },
    {
      id: 'teams',
      title: 'Teams',
      items: [
        { label: 'All Teams', path: '/teams' },
        { label: 'My Teams', path: '/user-teams' },
        { label: 'Team Detail' }
      ]
    },
    {
      id: 'dashboard',
      title: 'Dashboard',
      items: [
        { label: 'Dashboard Home', path: '/dashboard' }
      ]
    },
    {
      id: 'billing',
      title: 'Billing',
      items: [
        { label: 'Add Payment Card', path: '/card/add' },
        { label: 'Select Plan', path: '/plan' },
        { label: 'Subscribe Plan' }
      ]
    },
    {
      id: 'github',
      title: 'GitHub',
      items: [
        {
          label: 'Go API Backend',
          path: 'https://github.com/startersaas/startersaas-backend-go-api-main.git'
        },
        {
          label: 'Node API Backend',
          path: 'https://github.com/startersaas/startersaas-backend-node-api-main.git'
        },
        {
          label: 'React Frontend',
          path: 'https://github.com/startersaas/startersaas-frontend-react-spa.git'
        }
      ]
    }
  ];

  if (!display) return null;

  return (
    <AdaptiveLayout {...getAdaptiveLayoutProps(darkMode)}>
      <MenuContainer darkmode={darkMode.toString()}>
        {menuSections.map((section) => (
          <Box key={section.id}>
            <MenuButton
              darkmode={darkMode.toString()}
              onClick={(event) => handleMenuClick(event, section.id)}
              aria-controls={anchorEls[section.id] ? `${section.id}-menu` : undefined}
              aria-haspopup="true"
              aria-expanded={anchorEls[section.id] ? 'true' : undefined}
            >
              {section.title}
            </MenuButton>
            <Menu
              id={`${section.id}-menu`}
              anchorEl={anchorEls[section.id]}
              open={Boolean(anchorEls[section.id])}
              onClose={() => handleMenuClose(section.id)}
              MenuListProps={{
                'aria-labelledby': `${section.id}-button`,
                sx: { py: 0 }
              }}
              transformOrigin={{ horizontal: 'center', vertical: 'top' }}
              anchorOrigin={{ horizontal: 'center', vertical: 'bottom' }}
              sx={getMenuSx(darkMode)}
            >
              {section.items.map((item, idx) => (
                <StyledMenuItem
                  key={idx}
                  darkmode={darkMode.toString()}
                  onClick={() => handleMenuItemClick(item.path, section.id)}
                  disabled={!item.path}
                >
                  {item.label}
                </StyledMenuItem>
              ))}
            </Menu>
          </Box>
        ))}
      </MenuContainer>

      <Box sx={getVisitorCounterSx(darkMode)}>
        <VisitorCounter display={true} height={125} />
      </Box>
    </AdaptiveLayout>
  );
};

export default Footer;